package org.example.memora.task;

import lombok.extern.slf4j.Slf4j;
import org.example.memora.entity.PostLikeStat;
import org.example.memora.mapper.PostLikeStatMapper;
import org.example.memora.mapper.PostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.Set;

import static org.example.memora.common.constant.LikeConstant.POST_LIKE_TASK_TIME;

@Component
@Slf4j
public class PostLikeSyncTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PostLikeStatMapper postLikeStatMapper;
    @Autowired
    private PostMapper postMapper;

    // 每 60 秒执行一次同步任务
    @Scheduled(fixedDelay = POST_LIKE_TASK_TIME)
    @Transactional
    public void syncLikeCounts() {
        // 获取 Redis 中所有以 "post:like:count:" 开头的 key
        Set<String> keys = redisTemplate.keys("post:like:count:*");
        if (keys == null || keys.isEmpty()) {
            return;
        }
        for (String key : keys) {
            try {
                // 从 key 中解析出 postId
                String postId = key.substring("post:like:count:".length());
                String countStr = redisTemplate.opsForValue().get(key);
                int increment = (countStr != null) ? Integer.parseInt(countStr) : 0;
                if (increment <= 0) {
                    // 如果没有点赞计数则跳过
                    continue;
                }
                // 查询数据库中是否已有统计记录
                PostLikeStat stat = postLikeStatMapper.selectByPrimaryKey(postId);
                if (stat == null) {
                    // 如果没有记录，则创建新的统计记录
                    stat = new PostLikeStat();
                    stat.setPostId(postId);
                    stat.setLikeCount(increment);
                    stat.setUpdatedAt(Instant.now());
                    postLikeStatMapper.insert(stat);
                } else {
                    // 如果存在记录，则累加
                    stat.setLikeCount(stat.getLikeCount() + increment);
                    stat.setUpdatedAt(Instant.now());
                    postLikeStatMapper.updateByPrimaryKey(stat);
                }
                postMapper.incrementPostLikeCount(postId, increment);

                // 同步完成后清除该 Redis key，或者重置为 0
                redisTemplate.delete(key);
                log.info("更新数据库帖子点赞数");

            } catch (Exception e) {
                // 记录异常日志，防止同步任务因单个 key 失败而中断
                // 可以考虑使用日志记录工具，例如 log.error(...)
                e.printStackTrace();
            }
        }
    }
}
